package cc.linker.steplink.crm.merchant.controller.acs;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.acs.ExercisePcService;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchanth5.service.ExerciseService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动赠品
 */
@RequestMapping("/exercise")
@RestController
public class ExercisePcController {

    @Autowired
    private ExercisePcService exercisePcService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private ExerciseService exerciseService;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 添加活动赠品
     * @param param
     * @param session
     */
    @PostMapping("/addexercise")
    public void addExercise(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        // 判断购买的商品和赠送的商品不能重复
        if(!StringUtils.isEmpty(param.get("termContent")) && !StringUtils.isEmpty(param.get("giftContent"))) {
            if(param.get("termContent").toString().equals(param.get("giftContent").toString())){
                throw GlobalException.build("触发商品与赠品不能是同一个商品，请修改");
            }
        }
        // 判断活动名称是否有重复
        Integer ifRepeatTitleCount = exercisePcService.getRepeatTitleCount(param);
        if(ifRepeatTitleCount>0){
            throw GlobalException.build("活动名称已存在，请修改");
        }
        // 触发商品删除状态
        int state = 0;
        Integer termState = exercisePcService.getGoodsStateByID(param.get("termContent").toString());
        if(termState==1){
            throw GlobalException.build("触发商品已删除，请重新选择");
        }
        if("1".equals(param.get("giftType"))){
            // 赠品是知识付费时 是否被删除
            Integer giftState = exercisePcService.getGoodsStateByID(param.get("giftContent").toString());

            if(giftState==1){
                throw GlobalException.build("赠品已被删除，请重新选择");
            }
        }
        // 判断添加的商品是否还有库存
        if("1".equals(param.get("term").toString())){
            Integer termGoodsNum = exercisePcService.getGoodsNumByID(param.get("termContent").toString());
            state = termGoodsNum<1?2:0;
        }
        // 判断编辑时 发放的库存状态 且触发商品库存正常
        if(!StringUtils.isEmpty(param.get("id")) && state==0){
            Map<String,Object> nums = exercisePcService.getExerciseNumsById(param.get("id").toString());
            int  giftTotal = Integer.parseInt(nums.get("giftTotal").toString());// 发放总数
            int  giftSend = Integer.parseInt(nums.get("giftSend").toString());// 已发放数
            int fixGiftTotal = Integer.parseInt(param.get("giftTotal").toString());// 修改后的赠品总数
            if(fixGiftTotal<giftSend){
                throw GlobalException.build("发放总数不能小于已发放数量，请重新填写");
            }
            if(fixGiftTotal==giftSend){
                state = 2;
            }
        }

        param.put("state",state);

        // 判断时间是否有交集 相同的商品或赠品
        Integer ifRepeat = exercisePcService.IfRepeat(param);
        if(ifRepeat>0){
            throw GlobalException.build("不能提交时间段交集内重复的商品或者赠品");
        }
        if (StringUtils.isEmpty(param.get("id"))) {
            exercisePcService.addExercise(param);
        } else {
            exercisePcService.updateExercise(param);
        }
    }

    /**
     * 获取活动赠品详情
     * @param id
     * @param session
     * @return
     */
    @GetMapping("/getexercise")
    public Map<String,Object> getExercise(Integer id,HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String,Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        param.put("id", id);
        return exercisePcService.getExercise(param);
    }



    /**
     * 删除活动赠品
     * @param param
     * @param session
     */
    @PostMapping("/delexercise")
    public void delExercise(@RequestBody Map<String, Object> param, HttpServletRequest request)
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if(StringUtils.isEmpty(param.get("id"))){
            throw GlobalException.build("请选择一条记录");
        }
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        exercisePcService.delExercise(param);
    }

    /**
     * 活动赠品列表
     * @param status
     * @param keywords
     * @param pageIndex
     * @param pageSize
     * @param session
     * @return
     */
    @GetMapping("/list")
    public PageInfo List(
            @RequestParam(value = "status", defaultValue = "0", required = false) Integer status,
            @RequestParam(value = "keywords", defaultValue = "", required = false) String keywords,
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            HttpServletRequest request
    )
    {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String,Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        boolean ifSaler = userinfo.getSaler();
        if (ifSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("customerId", customerId);
        } else {
            param.put("customerId", orgId);
        }
        param.put("orgId", orgId);
        param.put("status", status);
        param.put("keywords", keywords);
        PageHelper.startPage(pageIndex,pageSize);
        return new PageInfo<>(exercisePcService.list(param));
    }


    /**
     * 通过订单查赠品
     * @param param
     * @param session
     * @return
     */
    @PostMapping("/getexercisebyorder")
    public List<Map<String,Object>> getExerciseByOrder(@RequestBody Map<String, Object> param,HttpServletRequest request){
        if(StringUtils.isEmpty(param.get("orderSn")) && StringUtils.isEmpty(param.get("orderId"))){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        param.put("orgId",userinfo.getOrgId());
        return exerciseService.getExerciseByOrder(param);
    }
}
